package wrapper

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

/**
 * description：
 * <p>
 * </p>
 * change history:
 * date                      defect#    person       comments
 * -------------------------------------------------------------<p>
 * 2023/9/28 10:52          ********    kong.ruo    create file.
 *
 * @author kong.ruo
 * @date 2023/9/28 10:52
 *
 * @since go 1.20
 */

// S2I convert string array to int array
func S2I(ir []int) (sr []string) {
	sr = make([]string, len(ir))

	for i, num := range ir {
		sr[i] = strconv.Itoa(num)
	}
	return
}

// FormatSlice string array to flat map
func FormatSlice(list []string, mode string) string {
	if len(list) == 0 {
		return " * "
	}
	return strings.Join(list, mode)
}

func TypeCheck(v interface{}) interface{} {
	if vs, ok := v.(string); ok {
		return fmt.Sprintf("'%s'", vs)
	} else if vi, ok := v.(int); ok {
		return strconv.Itoa(vi)
	} else {
		return v
	}
}

// GetEntityField reflect get entity fields key and value
func GetEntityField(entity interface{}) map[string]interface{} {
	// 使用反射获取结构体信息
	ev := reflect.ValueOf(entity)
	et := ev.Type()
	res := make(map[string]interface{})

	//var fieldCount int
	// check is or not struct
	if et.Kind() != reflect.Struct {
		if et.Kind() == reflect.Ptr && et.Elem().Kind() == reflect.Struct {
			// it's ptr
			ev = ev.Elem()
			et = et.Elem()
		} else {
			return nil
		}
	}
	searchField(ev, res)
	return res
}

func searchField(val reflect.Value, kv map[string]interface{}) {
	ev := val
	et := val.Type()
	for i := 0; i < val.NumField(); i++ {
		field := et.Field(i)
		value := ev.Field(i)
		// check field
		if value.Kind() == reflect.Struct {
			searchField(value, kv)
		} else {
			kv[field.Name] = value.Interface()
		}

	}
}
